package com.note.app.listener;

import com.note.app.service.SearchService;
import com.note.common.domain.Note;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Primary;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * 笔记变更监听器，用于自动索引笔记
 */
@Slf4j
@Component
public class NoteChangeListener {

    private final SearchService searchService;

    public NoteChangeListener(@Qualifier("searchServiceImpl") SearchService searchService) {
        this.searchService = searchService;
    }

    /**
     * 笔记创建或更新事件监听
     *
     * @param note 笔记对象
     */
    @Async
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void onNoteCreatedOrUpdated(Note note) {
        log.debug("收到笔记变更事件: noteId={}", note.getId());
        try {
            searchService.indexNote(note);
        } catch (Exception e) {
            log.error("笔记索引失败: " + e.getMessage(), e);
        }
    }

    /**
     * 笔记删除事件监听
     *
     * @param noteId 笔记ID
     */
    @Async
    @EventListener
    public void onNoteDeleted(Long noteId) {
        log.debug("收到笔记删除事件: noteId={}", noteId);
        try {
            searchService.deleteNoteIndex(noteId);
        } catch (Exception e) {
            log.error("笔记索引删除失败: " + e.getMessage(), e);
        }
    }
} 